#include "Uart4Task.h"
#include "Uart4Data.h"
#include "UartDMARcv_Proc.h"
#include "string.h"
#include "DeviceInfo.h"

#include "Fifo.h"
#include "wh_lte_driver.h"

static void StartUart4Task(const void *pvParameters);
static void StartUart4SendTask(const void *arg);
static void StartUart4CommandProcTask(const void *arg);


extern UART_HandleTypeDef huart4;
UartProcInfo uart4RcvItInfo = {.cu32RecvBufSize = UART4_BUF_SIZE};
uint8_t uart4Buff[UART4_BUF_SIZE] = { 0x0 };
osThreadId Uart4TaskHandle; 
osThreadDef(Uart4TaskId, StartUart4Task, osPriorityNormal, 1, 1024);

osMessageQId g_Uart4MsgQueue;
osMessageQDef(g_Uart4MsgQueue, 5, uint32_t);


osMessageQId g_SvrCmdProcMsgQueue;
osMessageQDef(g_SvrCmdProcMsgQueue, 5, uint32_t);

osThreadId Uart4CommandProcTaskHandle; 
osThreadDef(Uart4CommandProcTaskId, StartUart4CommandProcTask, osPriorityNormal, 1, 1024);

osThreadId Uart4SendTaskHandle; 
osThreadDef(Uart4SendTaskId, StartUart4SendTask, osPriorityNormal, 1, 1024);

#define SVRCMDDATA_FIFO_SIZE	512
static uint8_t *SvrCmdDataFifo = NULL;

static bool b4GModuleConfiged = false;

bool Uart4TaskInit(void)
{
	//创建数据指令执行任务
	g_SvrCmdProcMsgQueue = osMessageCreate(osMessageQ(g_SvrCmdProcMsgQueue), NULL);
	
	Uart4CommandProcTaskHandle = osThreadCreate(osThread(Uart4CommandProcTaskId), NULL);
	if(Uart4CommandProcTaskHandle == NULL)
	{
		return false;
	}
	
	//创建串口4接收数据任务
	g_Uart4MsgQueue = osMessageCreate(osMessageQ(g_Uart4MsgQueue), NULL);
	
	Uart4TaskHandle = osThreadCreate(osThread(Uart4TaskId), NULL);
	if(Uart4TaskHandle == NULL)
	{
		return false;
	}
	
	//创建串口4定时发送任务
	Uart4SendTaskHandle = osThreadCreate(osThread(Uart4SendTaskId), NULL);
	if(Uart4SendTaskHandle != NULL)
	{
		return false;
	}
	
	return true;
}


static uint8_t u8ProtolVldData[512] = {0};
static ProtolMachine* pUart4Pack = NULL;
static CommandInfo *cmd_infos = NULL;

static bool bIsSendExitByPassMode = false;
static bool bIsSendEchoOffCmd = false;
static bool bIsSendSetServerBCmd = false;
static bool bIsSendEnterByPassMode = false;
/**
  * @brief  Milk task
  * @param  pvParameters not used
  * @retval None
  */
static void StartUart4Task(const void *pvParameters)
{
	pUart4Pack = InitUart4Data();

	osEvent evt;
	uint32_t u32DataLength = 0;
	uint8_t u8PackCnt = 0;
	uint16_t u16LengthContent[10] = {0};
	uint32_t u32Uart4Timeout = 5000;

	InitUartProcInfo(&uart4RcvItInfo, &huart4, 
		UART4_BUF_SIZE, uart4Buff, g_Uart4MsgQueue);
	
	__HAL_UART_ENABLE_IT(&huart4, UART_IT_IDLE);
	HAL_UART_Receive_DMA(&huart4, uart4Buff, UART4_BUF_SIZE);
	
	osMessageQId msgQnModel4GId = getModel4GControlMsgQueneID();
	
	if(pUart4Pack)
		cmd_infos = pUart4Pack->cmdInfos;
	
	void Uart4SendData(uint8_t *data, uint32_t length);
	setUartSendPort(Uart4SendData);
	
	while(1)
	{
		evt = osMessageGet(g_Uart4MsgQueue, u32Uart4Timeout);
		
		if (evt.status == osEventMessage) 
		{
			u32DataLength = (uint32_t)evt.value.p;
			
			//如果4G模块已经初始化了（关闭回显，SocketA链接到有人云，SocketB链接到
			//自己的服务器
			if(b4GModuleConfiged)
			{
				ProtolMachineDecode(pUart4Pack, uart4Buff, u32DataLength,
						u8ProtolVldData,  u16LengthContent, &u8PackCnt);

				if(u8PackCnt > 0)
				{
					for(int i = 0; i < u8PackCnt; i ++)
					{
						fifo_in((struct fifo*)SvrCmdDataFifo, u8ProtolVldData, u16LengthContent[i]);
						osMessagePut(g_SvrCmdProcMsgQueue, u16LengthContent[i], 100);
					}
				}
			}
			else
			{
				if(u32DataLength > 0)
				{
					setModel4GBuff(uart4Buff, u32DataLength);
					osMessagePut(msgQnModel4GId, u32DataLength, 100);
					b4GModuleConfiged = getModelStartupDone();
				}
			}
		}
		else if(evt.status == osEventTimeout)
		{
			
		}
	}
}

static uint8_t u8ProcBuf[512] = {0};

static void StartUart4CommandProcTask(const void *arg)
{
	osEvent evt;
	uint32_t u32DataLength = 0;
	
	SvrCmdDataFifo = (uint8_t *)fifo_alloc(SVRCMDDATA_FIFO_SIZE);
	
	if(SvrCmdDataFifo)
	{
		while(1)
		{
			evt = osMessageGet(g_SvrCmdProcMsgQueue, 5000);
			
			if (evt.status == osEventMessage) 
			{
				u32DataLength = (uint32_t)evt.value.p;
				fifo_out((struct fifo*)SvrCmdDataFifo, (void *)u8ProcBuf, u32DataLength);
				
				if(cmd_infos)
				{
					int cmdIndex = GetCommandIndex(u8ProcBuf[1], cmd_infos);
					if(cmdIndex >= 0 && pUart4Pack)
					{
						pUart4Pack->cmdInfos[cmdIndex].tCommandCallback(u8ProcBuf, u32DataLength);
					}
						
				}
			}
			else if(evt.status == osEventTimeout)
			{
				
			}
		}
	}
	
}

extern bool u8ServerResponse;
static void StartUart4SendTask(const void *arg)
{
	uint32_t u32Time500msFirstStart = 1;
	uint32_t u32Time500msTimestamp = 0;
	
	uint32_t u32HeartBeat5sFirstStart = 1;
	uint32_t u32HeartBeat5sTimestamp = 0;
	
	while(1)
	{
		if(b4GModuleConfiged)
		{
			if(u32Time500msFirstStart)
			{
				u32Time500msFirstStart = 0;
				u32Time500msTimestamp = HAL_GetTick();
			}
			else if(HAL_GetTick() - u32Time500msTimestamp > 500)
			{
				u32Time500msFirstStart = 1;
			}
			
			if(u32HeartBeat5sFirstStart)
			{
				u32HeartBeat5sFirstStart = 0;
				u32HeartBeat5sTimestamp = HAL_GetTick();
			}
			else if(HAL_GetTick() - u32HeartBeat5sTimestamp > 5000)
			{
				//如果登陆成功
				if(canDeviceLoginOK())
				{
					//如果需要升级
					if(getDevNeedUpdate() && (u8ServerResponse == false))
					{
						RequestDevicePrepareUpdate();
					}
				}
				else
				{
					TryDeviceLogin();
				}
				u32HeartBeat5sFirstStart = 1;
			}
			
		}
		

		
		osDelay(100);
	}

}

